class BaiVietController < ApplicationController
  def index
    @danh_muc = DanhMuc.find_by_slug(params[:danh_muc_slug]) || not_found
    @bai_viet = BaiViet.find_by_slug(params[:bai_viet_slug])
    @ngon_ngu = I18n.locale.to_s
    if (@bai_viet.danh_muc.id != @danh_muc.id)
      #not_found
    end
    @danh_muc_ngon_ngu = @danh_muc.danh_muc_ngon_ngus.select{ |v| v.ngon_ngu == @ngon_ngu }
    if (@danh_muc_ngon_ngu.empty?)
      @danh_muc_ngon_ngu = @danh_muc.danh_muc_ngon_ngus[0]
    else
      @danh_muc_ngon_ngu= @danh_muc_ngon_ngu[0]
    end
    
    @bai_viet_moi = BaiViet.where(
    :danh_muc_id => @danh_muc.id, 
    :dang_kich_hoat => true, 
    :ngon_ngu => @ngon_ngu
    ).order(:created_at => "desc").limit(10).all
    
    @title = @bai_viet.tieu_de
  end

  def danh_muc
    @trang = (params[:page].present? && params[:page].to_i > 1 ?  params[:page] : 1).to_i
    @danh_muc = DanhMuc.find_by_slug(params[:danh_muc]) || not_found
    @ngon_ngu = I18n.locale.to_s
    @danh_muc_ngon_ngu = @danh_muc.danh_muc_ngon_ngus.select{ |v| v.ngon_ngu == @ngon_ngu }
    if (@danh_muc_ngon_ngu.empty?)
      @danh_muc_ngon_ngu = @danh_muc.danh_muc_ngon_ngus[0]
    else
      @danh_muc_ngon_ngu= @danh_muc_ngon_ngu[0]
    end
    
    @so_bai_moi_trang = CauHinh.gia_tri('bai_viet_so_luong_tren_trang', 5).to_i

    query = BaiViet.where(:danh_muc_id => @danh_muc.id, :dang_kich_hoat => true, :ngon_ngu => @ngon_ngu)

    @bai_viets = query.paginate(
      :order => :created_at.desc,
      :per_page => @so_bai_moi_trang,
      :page => @trang
    )
    @co_trang_sau = !query.paginate(
      :order => :created_at.desc,
      :per_page => @so_bai_moi_trang,
      :page => @trang + 1
    ).empty?
    
    # @bai_viets = @bai_viets + @bai_viets + @bai_viets + @bai_viets
    @co_trang_truoc = @trang > 1
    @index_dau_tien = (@trang - 1) * 20
    @title = @danh_muc_ngon_ngu.ten
  end
end
